package Cantella::DJabberd::Store::Result::Vhost;

use base qw/DBIx::Class::Core/;
use metaclass 'Reaction::Meta::Class';
use Moose;

use MooseX::Types::Moose qw(ArrayRef Int);
use Reaction::Types::Core qw(NonEmptySimpleStr);
use Cantella::DJabberd::Types qw/JIDDomain/;

use aliased 'Cantella::DJabberd::Store::Result::UserJid';
#use aliased 'Cantella::DJabberd::Store::Result::VhostBridge';
use aliased 'Cantella::DJabberd::Store::Result::ExternalComponent';

use namespace::clean -except => [ 'meta' ];

has id       => (is => 'ro', required => 1, isa => Int);
has hostname => (is => 'rw', required => 1, isa => JIDDomain);
has external_components => (isa => ArrayRef, reader => 'get_external_components');

#has jids
#has bridged_hosts => (isa => ArrayRef, reader => 'get_bridged_hosts');

{
  no warnings 'redefine';
  *get_external_components = sub { [ shift->external_components->all ] };
 # *bridged_hosts = sub { [ shift->get_bridged_hosts->all ] };
}

__PACKAGE__->table('virtual_hosts');
__PACKAGE__->add_columns
  (
   id       => {
                data_type => "INT",
                size => 10,
                default_value => undef,
                is_nullable => 0,
                is_auto_increment => 1,
                extra => { unsigned => 1 },
               },
   hostname => {
                data_type => "VARCHAR",
                size => 255,
                default_value => "",
                is_nullable => 0,
               },
  );

__PACKAGE__->set_primary_key('id');
__PACKAGE__->add_unique_constraint(hostname => ['hostname']);
__PACKAGE__->has_many(jids => UserJid, {'foreign.domain_id' => 'self.id'});
__PACKAGE__->has_many(external_components => ExternalComponent, 
                      { 'foreign.vhost_id' => 'self.id' });
#__PACKAGE__->has_many(bridged_hosts => VhostBridge,
#                      [ { vhost1_id => 'id' }, { vhost2_id => 'id' } ]);

#__PACKAGE__->has_many(bridged_hosts => VhostBridge,
#                      { -or => [ vhost1_id => 'id',  vhost2_id => 'id' ]});


#try to make this a has_many or m2m or whatever so we can use the reflector
# sub bridged_hosts{
#   my $self = shift;
#   my $schema = $self->result_source->schema;
#   my $rs = $schema->resultset('VhostBridge');
#   my $id = $self->id;
#   my @ids = $rs->search({ -or =>[ vhost1_id => $id,  vhost2_id => $id ]})->all;
#   my $result = $schema->resultset('Vhost')->search_rs({id => {-in => \@ids}});
#   return @_ > 0 ? $result->search_rs(@_) : $result;
# }

sub display_name { shift->hostname }

__PACKAGE__->meta->make_immutable(inline_constructor => 0);

1;
